package com.witmore.neutron.ai.web.wechat.service.impl;

import com.jk.common.response.ResponsePageResult;
import com.jk.common.response.ResponseResult;
import com.witmore.neutron.ai.web.filter.GlobalAccountSession;
import com.witmore.neutron.ai.web.wechat.client.McpStockAlertConfigClient;
import com.witmore.neutron.ai.web.wechat.dto.StockAlertConfigDTO;
import com.witmore.neutron.ai.web.wechat.dto.StockAlertConfigQueryDTO;
import com.witmore.neutron.ai.web.wechat.service.StockAlertConfigService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * 股票预警配置服务实现类
 * 重构后通过MCP服务统一管理股票预警配置和定时任务
 * Author: 豆子高
 * Date: 2025/12/19
 * Refactored: 2025/01/27
 */
@Slf4j
@Service
public class StockAlertConfigServiceImpl implements StockAlertConfigService {

    @Autowired
    private McpStockAlertConfigClient mcpStockAlertConfigClient;

    @Override
    public ResponseResult<String> createAlertConfig(StockAlertConfigDTO configDTO) {
        Integer userId = GlobalAccountSession.getUserInfo().getScorpionUserId();
        if (userId == null) {
            log.error("用户未登录，无法创建预警配置");
            return ResponseResult.fail(500, "用户信息异常，无法创建预警配置");
        }

        try {
            log.info("Web服务批量创建股票预警配置，转发到MCP服务: userId={}", userId);

            // 解析股票代码列表，转换为逗号分隔的字符串
            Map<String, String> stockMap = configDTO.getStringStringMap();
            String stockCodes = String.join(",", stockMap.keySet());

            // 调用MCP服务批量创建股票配置
            return mcpStockAlertConfigClient.batchSaveOrUpdateAlertConfig(
                    userId.longValue(),
                    stockCodes,
                    configDTO.getRiseRatio(),
                    configDTO.getFallRatio(),
                    configDTO.getPushFrequency() != null ? configDTO.getPushFrequency() : 30
            );

        } catch (Exception e) {
            log.error("创建预警配置失败", e);
            return ResponseResult.fail(500, "创建失败：" + e.getMessage());
        }

    }

    @Override
    public ResponseResult<String> updateAlertConfig(StockAlertConfigDTO configDTO) {
        Integer userId = GlobalAccountSession.getUserInfo().getScorpionUserId();
        if (userId == null) {
            log.error("用户未登录，无法更新预警配置");
            return ResponseResult.fail(500, "用户信息异常，无法更新预警配置");
        }

        try {
            log.info("Web服务更新股票预警配置，转发到MCP服务: userId={}, configId={}", userId, configDTO.getId());

            // 先通过MCP服务获取配置信息，同时进行权限检查
            StockAlertConfigDTO existingConfig = mcpStockAlertConfigClient.getAlertConfigById(
                    userId.longValue(), configDTO.getId());
            if (existingConfig == null) {
                log.error("预警配置不存在或无权限修改，id: {}, userId: {}", configDTO.getId(), userId);
                return ResponseResult.fail(500, "更新失败：无此配置");
            }

            // 调用MCP服务更新配置（MCP服务会自动更新定时任务）
            return mcpStockAlertConfigClient.saveOrUpdateStockAlertConfig(
                    userId.longValue(),
                    existingConfig.getStockCode() != null ? existingConfig.getStockCode() : existingConfig.getStockCodes(),
                    configDTO.getRiseRatio(),
                    configDTO.getFallRatio(),
                    configDTO.getPushFrequency() != null ? configDTO.getPushFrequency() : 30,
                    configDTO.getAlertEnabled()
            );

        } catch (Exception e) {
            log.error("更新预警配置失败", e);
            return ResponseResult.fail(500, "更新失败：" + e.getMessage());
        }
    }

    @Override
    public ResponseResult<String> deleteAlertConfig(Long id) {
        Integer userId = GlobalAccountSession.getUserInfo().getScorpionUserId();
        if (userId == null) {
            log.error("用户未登录，无法删除预警配置");
            return ResponseResult.fail(500, "用户信息异常，无法删除预警配置");
        }

        try {
            log.info("Web服务删除股票预警配置，转发到MCP服务: userId={}, configId={}", userId, id);

            // 先通过MCP服务获取配置信息，同时进行权限检查
            StockAlertConfigDTO configToDelete = mcpStockAlertConfigClient.getAlertConfigById(
                    userId.longValue(), id);
            if (configToDelete == null) {
                log.error("预警配置不存在或无权限删除，id: {}, userId: {}", id, userId);
                return ResponseResult.fail(400, "预警配置不存在或无权限删除");
            }

            // 调用MCP服务删除配置（MCP服务会自动停止定时任务）
            return mcpStockAlertConfigClient.deleteStockAlertConfig(
                    userId.longValue(),
                    configToDelete.getStockCode() != null ? configToDelete.getStockCode() : configToDelete.getStockCodes()
            );

        } catch (Exception e) {
            log.error("删除预警配置失败", e);
            return ResponseResult.fail(500, "删除预警配置失败");
        }
    }

    @Override
    public ResponseResult<StockAlertConfigDTO> getAlertConfigById(Long id) {
        Integer userId = GlobalAccountSession.getUserInfo().getScorpionUserId();
        if (userId == null) {
            log.error("用户未登录，无法获取预警配置");
            return ResponseResult.fail(500, "用户信息异常，无法获取预警配置");
        }

        try {
            log.info("Web服务获取股票预警配置，调用MCP服务: userId={}, configId={}", userId, id);

            // 调用MCP服务获取配置
            return ResponseResult.success(mcpStockAlertConfigClient.getAlertConfigById(userId.longValue(), id));

        } catch (Exception e) {
            log.error("获取预警配置失败", e);
            return ResponseResult.fail(500, "获取失败：" + e.getMessage());
        }
    }

    @Override
    public ResponsePageResult<StockAlertConfigDTO> queryAlertConfigs(StockAlertConfigQueryDTO queryDTO) {
        Integer userId = GlobalAccountSession.getUserInfo().getScorpionUserId();
        if (userId == null) {
            log.error("用户未登录，无法查询预警配置");
            return ResponsePageResult.fail(500, "用户信息异常，无法查询预警配置");
        }

        try {
            log.info("Web服务分页查询股票预警配置，调用MCP服务: userId={}, queryDTO={}", userId, queryDTO);

            // 调用MCP服务分页查询
            return mcpStockAlertConfigClient.queryAlertConfigs(
                            userId.longValue(),
                            queryDTO.getStockCode(),
                            queryDTO.getStockName(),
                            queryDTO.getAlertEnabled(),
                            queryDTO.getPage(),
                            queryDTO.getSize()
                    );

        } catch (Exception e) {
            log.error("查询预警配置失败", e);
            return ResponsePageResult.fail(500, "查询失败：" + e.getMessage());
        }
    }

}
